package org.light4admin.modules.system.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import org.light4admin.common.Constants;
import org.light4admin.common.base.Response;
import org.light4admin.modules.system.contract.req.SysLoginReq;
import org.light4admin.modules.system.domain.vo.LoginUser;
import org.light4admin.modules.system.service.impl.RedisService;
import org.light4admin.modules.system.service.impl.SysLoginService;
import org.light4admin.modules.system.service.impl.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户登录相关
 *
 * @author light4admin
 */
@RestController
public class SysLoginController {

    @Value("${verify.captchaType}")
    private String captchaType;
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    @PostMapping("/auth/login")
    public Response<Map<String, Object>> login(@Validated @RequestBody SysLoginReq request) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(request);
        // 获取登录token
        Map<String, Object> dataMap = tokenService.createToken(userInfo);
        return Response.success(dataMap);
    }

    /**
     * 退登
     */
    @DeleteMapping("/auth/logout")
    public Response<Void> logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser)) {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
        }
        return Response.success();
    }

    /**
     * 刷新token有效期
     */
    @PostMapping("/auth/refresh")
    public Response<Void> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return Response.success();
        }
        return Response.success();
    }

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Response<Map> getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Response.failed(e.getMessage());
        }

        Map<String, String> dataMap = new HashMap();
        dataMap.put("uuid", uuid);
        dataMap.put("img", Base64.encode(os.toByteArray()));
        return Response.success(dataMap);
    }

}
